<template>
  <van-row class="order order-tab-box">
    <van-nav-bar
      fixed
      :z-index="100"
      title="订单中心"
      left-arrow
      @click-left="onClickLeft"
    />
    <van-tabs @click="onClick" v-model="active">
      <!-- 下拉刷新 -->
      <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
        
        <van-tab 
          v-for="(item,index) in productStatus"
          :key="index" 
          :title="item.title">

          <!-- 上拉加载 -->
          <van-list
            v-model="loading"
            :offset="50"
            :immediate-check="false"
            :finished="finished"
            :finished-text="!notList ? '没有更多了': ''"
            @load="onLoad">

            <!-- 内容 -->
            <div v-if="active != 4">
              <div v-for="(product, num) in orderList" :key="product.id" class="pro-container">
                <div class="status">{{proStatus[product.status]}}</div>
                <div>
                  <van-card
                    v-for="(item,index) in product.orderItemList"
                    :key="item.id"
                    :num="item.productQuantity"
                    :title="item.productName"
                    :price="item.productPrice"
                    :thumb="item.productPic"
                    @click="checkInfo(product.id)"
                  >
                    <div slot="tags">
                      <van-tag
                        plain
                        type="danger"
                        v-for="(item,index) in JSON.parse(item.productAttr)"
                        :key="index"
                      >{{item.key}}:{{item.value}}</van-tag>
                    </div>
                    <div
                      v-show="index == product.orderItemList.length-1"
                      slot="footer"
                      class="productSpec"
                    >
                      <!-- <div v-show="product.orderItemList">共{{product.orderItemList[0].productQuantity}}件商品</div> -->
                      <div>
                        应付款：￥
                        <span>{{product.payAmount}}</span>
                        (含运费￥{{product.freightAmount}})
                      </div>
                    </div>

                    <div slot="footer" v-show="index == product.orderItemList.length-1">
                      <div class="status" >售后状态：{{afterSaleStatus[product.orderItemList[0].serviceStatus]}}</div>
                      <van-button
                        v-for="(item,index) in proEventList[`event${product.status}`]"
                        :key="index"
                        size="mini"
                        :class="item == '立即付款' ? 'tored' : ''"
                        @click.stop="proEventClick(product,item,num)"
                      >{{item}}</van-button>
                      <!-- 已收货 && 未评价-->
                      <van-button v-if="product.status == 3 && item.commentStatus != 1" size="mini" @click.stop="proEventClick(item,'评价商品')">评价商品</van-button>
                    </div>
                  </van-card>
                </div>
              </div>
            </div>

            <!-- 待评价内容 -->
            <div v-else>
              <div v-for="(item, index) in evaluateList" :key="index" class="pro-container">
                <div class="status">已收货</div>
                <div>
                  <van-card
                    :key="item.id"
                    :num="item.productQuantity"
                    :title="item.productName"
                    :price="item.productPrice"
                    :thumb="item.productPic"
                    @click="checkInfo(item.orderId)"
                  >
                    <div slot="tags" v-if="item.productAttr">
                      <van-tag
                        plain
                        type="danger"
                        v-for="(product,i) in JSON.parse(item.productAttr)"
                        :key="i"
                      >{{product.key}}:{{product.value}}</van-tag>
                    </div>
                    <div
                      slot="footer"
                      class="productSpec"
                    >
                      <!-- <div v-show="product.orderItemList">共{{product.orderItemList[0].productQuantity}}件商品</div> -->
                      <div>
                        应付款：￥
                        <span>{{item.realAmount}}</span>
                      </div>
                    </div>

                    <div slot="footer">
                      <div class="status" >售后状态：{{afterSaleStatus[item.serviceStatus]}}</div>
                      <van-button size="mini" @click.stop="proEventClick(item,'评价商品')">评价商品</van-button>
                    </div>
                  </van-card>
                </div>
              </div>
            </div>
 
          </van-list>
          <div class="not-list" v-show="notList">
            <div>
              <van-icon name="todo-list-o" />
              <p>您还没有相关的订单</p>
            </div>
          </div>

        </van-tab>

        
      </van-pull-refresh>
      
    </van-tabs>
    <store-pay-dialog
      @getPayPassword="getPayPassword"
      @closeDialog="closeDialog" 
      @toPay="toPay" 
      :show="showPayDialog">
    </store-pay-dialog>
    <store-loding v-show="loding"></store-loding>
  </van-row>
</template>
<script>
import Vue from 'vue'
import { mapState, mapActions } from 'vuex'
// import storeScroller from '@/components/store-scroller'
import storeCard from '@/components/store-card'
import storePayDialog from '@/components/store-pay-dialog'
import storeLoding from '@/components/store-loding'
import { getClient } from '@/utils/util'
import { wxpay } from '@/utils/wxpay'
import {
  Tab,
  Tabs,
  NavBar,
  Card,
  Button,
  Tag,
  Row,
  Toast,
  Dialog,
  Icon,
  PullRefresh,
  List
} from 'vant'
Vue.use(NavBar)
  .use(Tab)
  .use(Tabs)
  .use(Card)
  .use(Button)
  .use(Tag)
  .use(Row)
  .use(Toast)
  .use(Dialog)
  .use(Icon)
  .use(PullRefresh)
  .use(List)
export default {
  name: 'order',
  components: {
    // storeScroller,
    storeCard,
    storePayDialog,
    storeLoding
  },
  data() {
    return {
      isLoading: false, // 下拉loading
      loading: false,   // 上拉loading
      active: 0, // Tab下标
      loding: false, // 加载中...
      productStatus: [
        { id: '0', title: '全部' },
        { id: '1', title: '待付款' },
        { id: '2', title: '待发货' },
        { id: '3', title: '待收货' },
        { id: '4', title: '待评价' }
      ],
      // 0->待付款；1->待发货；2->已发货；3->已收货；4->已关闭；5->已完成; 6->退款中
      proStatus: ['待付款', '已付款', '已发货', '已收货', '已关闭', '交易成功', '退款中'],
      /* 
        售后状态 
          无售后 = -1; 买家申请 = 0; 已同意 = 1; 已拒绝 = 2; 
          买家已发货 = 4; 买家已取消 = 5; 已确认收货 = 6; 售后退款完成 = 7;
      */
     afterSaleStatus: {
       '-1': '无售后',
        '0': '待处理',
        '1': '待退货',
        '2': '已拒绝',
        '4': '已退货',
        '5': '已取消',
        '6': '待退款',
        '7': '售后已完成'
      },
      proEventList: {
        event0: ['关闭订单', '立即付款'],
        event1: ['取消订单'],
        event2: ['查看物流', '确认收货'],
        event3: [],
        event4: ['删除订单'],
        event5: ['删除订单']
      },
      showPayDialog: false, //支付弹框默认隐藏
      patyType: '', //获取支付方式

      /***********联调用的的数据************* */
      pageNum: 1,
      channel: null,
      aliChannel: null,
      wxChannel: null,
      payParamsObj: {},
      isBalanceEnough: true
    }
  },
  created() {
    this.active = parseInt(this.$route.query.tabId)
    this.initData()
  },
  mounted() {
    this.onPlusReady(() => {
      plus.navigator.setStatusBarStyle('dark');
      this.getPayChannel()
    })
  },
  computed: {
    ...mapState({
      clientId: state => state.sys.clientId,
      userInfo: state => state.user.userInfo,
      orderList: state => state.order.orderList, // 列表数据
      evaluateList: state => state.order.evaluateList, // 待评价列表
      notList: state => state.order.notList, // 您还没有相关订单
      finished: state => state.order.finished, // 数据是否加载完(下拉刷新组件)
    })
  },
  methods: {
    ...mapActions('user', ['getUserInfo']),
    ...mapActions('order', ['getOrderList']),
    /*************返回点击事件***************/
    onClickLeft() {
      this.$router.push('/main/user')
    },

    /********初始化数据********/
    initData() {
      this.pageNum = 1
      this.getListData(this.active, 'click', this.pageNum)
    },

    /********获取列表数据********/ 
    getListData(active, eventName, pageNum) {
      this.getOrderList({active, eventName, pageNum})
        .then(()=> {
  
        })
        .finally(() => {
            this.isLoading = false // 下拉loading
            this.loading = false // 上拉loading
            this.loding = false
          })
    },

    /*************下拉刷新*************/ 
    onRefresh() {
      console.log('下拉')
      this.pageNum = 1 
      this.getListData(this.active, 'pull-down', this.pageNum)
      
    },

    /*************上拉加载*************/ 
    onLoad() {
      console.log('触底了')
      this.pageNum++
      this.getListData(this.active, 'pull-up', this.pageNum)
    },

    /*************tab切换标签点击事件*********/
    onClick(name) {
      if (this.$route.query.tabId == name) return
      document.documentElement.scrollTop = 0
      this.$router.replace({
        name: 'order',
        query: {
          tabId: name
        }
      })
      this.pageNum = 1
      this.getListData(name, 'click', this.pageNum)
    },

    /*************点击查看详情事件***************/
    checkInfo(orderId) {
      this.$router.push({
        name: 'orderinfo',
        query: {
          orderId
        }
      })
      // this.$store.commit('order/SET_CHECK_INFO_LIST', item)
    },

    /************产品按钮点击点击事件*********/
    proEventClick(product, event, index) {
      switch (event) {
        case '取消订单':
          this.confirmDialog('cancel', product.orderItemList)
          break
        case '删除订单':
          this.confirmDialog('delete', product.orderItemList, index)
          break
        case '关闭订单':
          this.confirmDialog('close', product.orderItemList)
          break
        case '查看物流':
          this.$store.commit('order/SET_CHECK_INFO_LIST', product)
          this.$router.push({
            name: 'productExpress',
            params: {
              id: product.id
            }
          })
          break
        case '评价商品':
          this.$store.commit('order/SET_CHECK_INFO_LIST', product)
          this.$router.push({
            name: 'comment',
            // params: {
            //   id: product.id
            // }
          })
          break
        case '退款':
          this.refundEvent(product)
          break
        case '退货退款':
          this.refundEvent(product)
          break
        case '立即付款':
          this.$store.dispatch('payChannel/getPayChannel').then(() => {
            this.showPayDialog = true
            this.isBalanceEnough =
              this.userInfo.amsAccount.balance >= product.payAmount
          })
          this.payParamsObj = {
            orderIds: product.orderItemList.map(item => item.orderId),
            sourceType: this.clientId
          }
          break
        case '确认收货':
          this.$store.commit('order/SET_CHECK_INFO_LIST', product.orderItemList[0])
          this.confirmDialog('confirmReceive', product.orderItemList)
          break
      }
    },

    /*******退款事件***** */
    refundEvent(p) {
      if (p.orderItemList[0].serviceStatus > -1) {
        Toast.fail('该产品已有售后处理中')
        return
      }
      this.$store.commit('order/SET_CHECK_INFO_LIST', p)
      this.$router.push({
        name: 'refund',
        params: {
          id: p.id
        }
      })
    },
    /***********点击取消订单和删除订单弹窗事件*********/
    confirmDialog(type, pArr, index) {
      let title = ''
      let message = ''
      if (type == 'cancel') {
        title = '取消订单'
        message = '您确定取消这个订单吗？'
      } else if (type == 'delete') {
        title = '删除订单'
        message = '您确定删除这个订单吗？'
      } else if (type == 'close') {
        title = '关闭订单'
        message = '您确定关闭这个订单吗？'
      } else if (type == 'confirmReceive') {
        title = '确认收货'
        message = '您确定已经收到货吗？'
      }
      Dialog.confirm({
        title,
        message
      })
        .then(() => {
          // on confirm
          let orderId = pArr[0].orderId
          if (type == 'cancel') {
            this.cancelOrder(orderId)
          } else if (type == 'delete') {
            this.deleteOrder(orderId, index)
          } else if (type == 'close') {
            this.closeOrder(orderId)
          } else if (type == 'confirmReceive') {
            this.confirmOrder(orderId)
          }
        })
        .catch(() => {
          // on cancel
        })
    },

    /***********取消订单事件*********/
    cancelOrder(orderId) {
      this.loding = true
      const params = {
        orderId
      }
      this.$http
        .post('/order/cancelOrder', params)
        .then(() => {
          this.initData()
        })
        .catch(error => {
          console.log(error)
        })
        .finally(() => {
          this.loding = false
        })
    },

    /***********关闭订单事件*********/
    closeOrder(orderId) {
      this.loding = true
      const params = {
        orderId
      }
      this.$http
        .post('/order/closeOrder', params)
        .then(() => {
          this.initData()
        })
        .catch(error => {
          console.log(error)
        })
        .finally(() => {
          this.loding = false
        })
    },

    /***********删除订单事件*********/
    deleteOrder(pid, index) {
      this.loding = true
      const params = {
        orderId: pid
      }
      this.$http
        .post('/order/deleteOrder', params)
        .then(() => {
          this.orderList.splice(index, 1)
        })
        .catch(error => {
          console.log(error)
        })
        .finally(() => {
          this.loding = false
        })
    },

    /*********确认收货事件******** */
    confirmOrder(orderId) {
      this.loding = true
      const params = {
        orderId
      }
      this.$http
        .post('/order/confirmReceiveOrder', params)
        .then(() => {
          this.$router.push({
            name: 'successfulOrder',
            // params: {
            //   pid: orderId
            // }
          })
        })
        .catch(error => {
          console.log(error)
          this.loding = false
        })
    },

    /*************支付弹框事件群start******/
    /***********隐藏弹框*********/
    closeDialog(bool) {
      // console.log(this.$route.path)
      this.showPayDialog = bool
    },
    /***********获取支付密码*********/
    getPayPassword(pw) {
      this.payParamsObj.password = pw
    },
    /***********订单中心-去支付*********/
    toPay(method, type, callback, hideRadio) {
        // method => 支付通道(WXPAY、ALIPAY、BALANCE), type => 支付方式(APP、H5)
        this.payType = method
        this.payParamsObj.methodType = type
        this.payParamsObj.clientId = getClient()
        if (this.payType == '' || !this.payType) {
          Toast.fail('请选择您需要的支付方式')
          return
        }
        if (this.payType == 'WXPAY') {
          this.payParamsObj.payType = 'WXPAY'
          this.channel = this.wxChannel
        } else if (this.payType == 'ALIPAY') {
          this.payParamsObj.payType = 'ALIPAY'
          this.channel = this.aliChannel
        } else if (this.payType == 'PCREDIT') {
          this.payParamsObj.payType = 'PCREDIT'
          this.channel = this.aliChannel
        } else {
          this.payParamsObj.payType = 'BALANCE'
          if (!this.isBalanceEnough) {
            Toast.fail('余额不足以支付该产品')
            if (typeof callback == 'function') {
              callback();
              hideRadio();
            }
            this.$router.push({
              name: 'order',
              query: {
                tabId: 0
              }
            })
            return
          }
        }
        this.$http.post('/trade/pay', this.payParamsObj).then(data => {
          if (this.payType == 'BALANCE') {
            this.showPayDialog = false
            Toast.success('支付成功')
            this.$router.push({
              name: 'order',
              query: {
                tabId: 0
              }
            })
            if (typeof callback == 'function') {
              callback()
              hideRadio()
            }
            return
          }

          // 支付宝(测试通过)
          if (this.payType == 'ALIPAY' || this.payType == 'PCREDIT') {
            if (this.clientId == 1) {
              let temPrams = data.info.info
              plus.payment.request(
                this.channel,
                temPrams,
                () => {
                  plus.nativeUI.alert('支付成功！', function() {
                    if (typeof callback == 'function') {
                      callback()
                      hideRadio()
                    }
                    this.$router.push({
                      name: 'order',
                      query: {
                        tabId: 0
                      }
                    })
                  })
                },
                error => {
                  plus.nativeUI.alert('支付失败：' + error.code)
                }
              )
            }
          }

          if (this.payType == 'WXPAY') {
            // App
            if (this.clientId == 1) {
              // App内使用H5方式支付
              if (type == 'H5') {
                // 接口返回来的微信H5支付的链接地址
                let payUrl = data.info.mweb_url;
                let self = plus.webview.currentWebview();
                let payView = plus.webview.create(payUrl, 'pay-url', {
                  top: '1000px', bottom: '1000px',
                  additionalHttpHeaders: { referer: process.env.VUE_APP_HOST }
                });
                self.append(payView);
              } else if(type == 'APP') {
                // App内使用原生方式
                let temPrams = data.info
                temPrams.timestamp = parseInt(data.info.timestamp)
                
                plus.payment.request(
                  this.channel,
                  temPrams,
                  () => {
                    plus.nativeUI.alert('支付成功！', function() {
                      if (typeof callback == 'function') {
                        callback()
                        hideRadio()
                      }
                      this.$router.push({
                        name: 'order',
                        query: {
                          tabId: 0
                        }
                      })
                    })
                  },
                  error => {
                    plus.nativeUI.alert('支付失败：' + error.code)
                  }
                )
              }
              return
            }
            // 网页 wap
            if (this.clientId == 2) {
              // 接口返回来的微信H5支付的链接地址
              let payUrl = data.info.mweb_url;
              window.location.href = payUrl
              return
            }
            // wx 内置浏览器
            if (this.clientId == 3) {
              wxpay(data.info, payResult => {
                if (payResult.err_msg == 'get_brand_wcpay_request:ok') {
                  Toast.success('支付成功')
                  this.$router.push({
                    name: 'order',
                    query: {
                      tabId: 0
                    }
                  })
                } else {
                  Toast.fail('支付失败')
                  this.$router.push({
                    name: 'order',
                    query: {
                      tabId: 0
                    }
                  })
                }
              })
              return
            }
          }
          if (typeof callback == 'function') {
            hideRadio();
          }
        })
          .catch(err => {
            if (this.payType == 'BALANCE' && err.errcode == 127) {
              Dialog.confirm({
                title: '提示',
                message: '密码输入错误',
                confirmButtonText: '重新输入'
              }).then(() => {
               
              }).catch(() => {
                if (typeof callback == 'function') {
                  callback();
                  hideRadio();
                  this.$router.push({
                    name: 'order',
                    query: {
                      tabId: 0
                    }
                  })
                }
              });
            } else if (this.payType == 'BALANCE') {
              if (typeof callback == 'function') {
                callback();
                hideRadio();
              }
              this.$router.push({
                name: 'order',
                query: {
                  tabId: 0
                }
              })
            }
            else {
              Toast.fail(err.message);
              this.$router.push({
                name: 'order',
                query: {
                  tabId: 0
                }
              })
              if (typeof callback == 'function') {
                hideRadio();
              }
            }
            this.showPayDialog = false
          })
      },

    /***********黄亮---点击支付按钮事件并获取支付方式*********/
    /* toPay(type) {
      this.payType = type
      console.log('sfsdf', this.payType)
      var requestUrl = null
      if (this.payType == 'WXPAY') {
        requestUrl = '/trade/pay'
        this.channel = this.wxChannel
        this.payParamsObj.channelId = 2
      } else if (this.payType == 'ALIPAYPAYS') {
        requestUrl = '/ali/pay'
        this.channel = this.aliChannel
        this.payParamsObj.channelId = 4
      } else {
        requestUrl = '/trade/pay'
        this.channel = this.wxChannel
        this.payParamsObj.channelId = 1
        if (!this.isBalanceEnough) {
          Toast.fail('余额不足以支付该产品')
          return
        }
      }

      this.$http.post(requestUrl, this.payParamsObj).then(data => {
        if (this.payType == 'BALANCE') {
          this.showPayDialog = false
          Toast.success('支付成功')
          this.initData()
          this.getUserInfo()
          return
        }
        let temPrams = data.info
        temPrams.timestamp = parseInt(data.info.timestamp)
        plus.payment.request(
          this.channel,
          temPrams,
          () => {
            this.$http
              .post('trade/tradeDetail', { tradeNo: temPrams.tradeNo })
              .then(() => {
                plus.nativeUI.alert('支付成功！', function() {
                  this.$router.push('/order')
                })
              })
          },
          error => {
            plus.nativeUI.alert('支付失败：' + error.code)
          }
        )
      })
    }, */


    /*******调用5+支付功能********** */
    getPayChannel() {
      // 获取支付通道
      plus.payment.getChannels(
        channels => {
          for (var i = 0; i < channels.length; i++) {
            if (channels[i].id == 'alipay') {
              this.aliChannel = channels[i]
            } else if (channels[i].id == 'wxpay') {
              this.wxChannel = channels[i]
            }
          }
        },
        function(e) {
          plus.nativeUI.alert('获取支付通道失败：' + e.message)
        }
      )
    },
    /*************支付弹框事件群end******/
 
  },
  watch: {
    /* active(newValue, oldValue) {
      this.pageNum = 1
      this.onClick(newValue)
    } */
  }
}
</Script>
<style>
html{
  height: 100%;
}
</style>
<style lang="scss" scoped>
.van-pull-refresh{
  padding-left: 15px;
  padding-right: 15px;
  min-height: calc(100vh - 115px)
}
.order {
  padding-top: 115px;
  /deep/.van-tabs__line {
    background-color: #FE472D;
  }
  /deep/.van-loading__circular {
    color: #969799;
  }
  /deep/.van-tabs--line .van-tabs__wrap {
    position: fixed;
    left: 0;
    right: 0;
    top: 66px;
    z-index: 10;
  }
  /deep/.van-tabs__content {
    width: 100%;
    .van-button {
      margin-left: 5px;
      width: 70px;
      height: 26px;
      line-height: 26px;
      border-radius: 15px;
      border: 1px solid #ccc;
      color: $font-color-gray;
    }
    .tored {
      border: 1px solid $primary-clr;
      color: $primary-clr;
    }
  }
  /deep/.van-tabs__nav {
    .van-tab {
      flex-basis: 20% !important;
    }
  }

  .not-list{
    color: #7d7e80;
    text-align: center;
    height: 160px;
    padding-top: 60px;
    .van-icon{
      font-size: 18px;
    }
  }
  .mayLike {
    .mayLikeTitle {
      display: flex;
      align-items: center;
      height: 50px;
      justify-content: center;
      color: $red;
      font-size: 16px;
      .leftLine,
      .roghtLine {
        height: 1px;
        width: 20px;
        background: $red;
        position: relative;
        &::before {
          content: '';
          position: absolute;
          top: -2px;
          width: 4px;
          height: 4px;
          border-radius: 50%;
          background: $red;
        }
      }
      .leftLine {
        margin-right: 5px;
        &::before {
          left: 0;
        }
      }
      .roghtLine {
        margin-left: 5px;
        &::before {
          right: 0;
        }
      }
    }
    .store-card {
      margin-top: 0;
    }
  }
  .van-tab__pane {
    .pro-container {
      margin-top: 8px;
      border-radius: 5px;
      background-color: #fff;
    }

    .van-card {
      margin: 0;
      background: #fff;
      border-radius: 0 0 8px 8px;
      .productSpec {
        div {
          display: inline;
          line-height: 40px;
          span {
            font-size: 20px;
          }
        }
      }
    }
    .status {
      text-align: right;
      padding-right: 10px;
      height: 30px;
      line-height: 30px;
      background: #fff;
      color: $primary-clr;
      border-radius: 8px 8px 0 0;
    }
    .van-tag--danger.van-tag--plain, .van-card__price {
      color: $primary-clr;
    }
  }
}
</style>
